<template>
  <div class="login">
    <el-row>
      <el-col :span="12" class="left">
        <div class="leftCont">
          <div class="logoName">
            <img src="../assets/images/logoName.png" alt="" />
          </div>
          <div class="yingwenIcon">
            <img src="../assets/images/yingwenIcon.png" alt="" />
          </div>
          <div class="leftImg">
            <img src="../assets/images/leftImg.png" alt="" />
          </div>
        </div>
      </el-col>
      <el-col :span="12" class="right">
        <el-form
          ref="loginForm"
          :model="loginForm"
          :rules="loginRules"
          class="login-form"
        >
          <h6 class="englishSize">WELCOME</h6>
          <h3 class="title">迎客到家管理系统</h3>
          <el-form-item prop="username">
            <el-input
              v-model="loginForm.username"
              type="text"
              auto-complete="off"
              placeholder="账号"
              class="intHeight"
            >
              <svg-icon
                slot="prefix"
                icon-class="user"
                class="el-input__icon input-icon"
              />
            </el-input>
          </el-form-item>
          <el-form-item prop="password">
            <el-input
              v-model="loginForm.password"
              type="password"
              auto-complete="off"
              placeholder="密码"
              @keyup.enter.native="handleLogin"
            >
              <svg-icon
                slot="prefix"
                icon-class="password"
                class="el-input__icon input-icon"
              />
            </el-input>
          </el-form-item>
          <el-form-item prop="code">
            <el-input
              v-model="loginForm.code"
              auto-complete="off"
              placeholder="验证码"
              style="width: 63%"
              @keyup.enter.native="handleLogin"
            >
              <svg-icon
                slot="prefix"
                icon-class="validCode"
                class="el-input__icon input-icon"
              />
            </el-input>
            <div class="login-code">
              <img :src="codeUrl" @click="getCode" class="login-code-img" />
            </div>
          </el-form-item>
          <div class="checkPass">
            <el-checkbox
              v-model="loginForm.rememberMe"
              style="margin: 0px 0px 25px 0px;color:#666"
              >记住密码</el-checkbox
            >
            <div @click="forgetPass">忘记密码</div>
          </div>
          <el-form-item style="width: 100%">
            <el-button
              class="buttonLogo"
              :loading="loading"
              size="medium"
              type="warning"
              style="width: 100%"
              @click.native.prevent="handleLogin"
            >
              <span v-if="!loading">登 录</span>
              <span v-else>登 录 中...</span>
            </el-button>
          </el-form-item>
        </el-form></el-col
      >
    </el-row>
    <el-dialog
      :title="title"
      :close-on-click-modal="false"
      :visible.sync="open"
      width="400px"
      style="top: 14%"
      append-to-body
      class="forgetPassBox"
      @close="handleClose"
    >
      <div style="margin-top: 0">
        <label style="margin-top: 0">用户名</label>
        <el-input
          v-model="userName"
          placeholder="请输入用户名"
          onkeyup="this.value=this.value.replace(/[\u4E00-\u9FA5]/g,'')"
        ></el-input>
      </div>
      <div>
        <label>验证码</label>
        <div class="box-input">
          <el-input type="text" autoComplete="off" v-model="numCode" placeholder="短信验证码"/>
          <div class="e-code" :class="{gCode:!codeState}" @click="sendloginCode">{{codeText}}</div>
        </div>
      </div>
      <div>
        <label>新密码</label>
        <el-input
          autocomplete="new-password"
          v-model="newPassword"
          placeholder="请输入新密码"
          class="intMargin"
          @blur="passBlur"
          onkeyup="this.value=this.value.replace(/[\u4E00-\u9FA5]/g,'')"
          type="password"
        ></el-input>
      </div>
      <div>
        <label>确认新密码</label>
        <el-input
          v-model="againPassword"
          placeholder="请再次输入新密码"
          onkeyup="this.value=this.value.replace(/[\u4E00-\u9FA5]/g,'')"
          type="password"
        ></el-input>
        <em><i>*</i>密码长度不低于6位，且包含数字、字母和特殊符号三种</em>
      </div>
      <div class="submitBtn">
        <el-button type="primary" @click="submitBtnClick">确认</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getCodeImg, appUpdatePassword,enrollPhone } from "@/api/login";
import Cookies from "js-cookie";
import { encrypt, decrypt } from "@/utils/jsencrypt";

export default {
  name: "Login",
  data() {
    return {
      open: false,
      title: "",
      oldPassword: "",
      newPassword: "",
      againPassword: "",
      codeUrl: "",
      cookiePassword: "",
      userName: "",
      codeState: true,
      codeText: '获取短信验证码',
      regText: '用户注册',
      numCode:'',

      loginForm: {
        username: "",
        password: "",
        rememberMe: false,
        code: "",
        uuid: "",
      },
      loginRules: {
        username: [
          { required: true, trigger: "blur", message: "用户名不能为空" },
        ],
        password: [
          { required: true, trigger: "blur", message: "密码不能为空" },
        ],
        code: [{ required: true, trigger: "blur", message: "验证码不能为空" }],
      },
      loading: false,
      redirect: undefined,
    };
  },
  watch: {
    $route: {
      handler: function (route) {
        this.redirect = route.query && route.query.redirect;
      },
      immediate: true,
    },
  },
  created() {
    this.getCode();
    this.getCookie();

  },
  methods: {
    sendloginCode() {
      if (!this.userName) {
        this.$message.error('请输入用户名！')
        return
      }
      if (!this.codeState) return;
      this.codeState = false
      let time = 59
      enrollPhone({
        phone: this.userName,
        num: 1
      }).then(res => {
        console.log(res)
      })
      var n = setInterval(() => {
        this.codeText = time + 's后重新获取';
        time--
        if (time < 0) {
          this.codeText = '重新获取';
          this.codeState = true
          clearInterval(n)
        }
      }, 1000)
    },
    //弹窗关闭
    handleClose() {
      this.oldPassword = "";
      this.newPassword = "";
      this.againPassword = "";
      this.userName = "";
    },
    getCode() {
      getCodeImg().then((res) => {
        this.codeUrl = "data:image/gif;base64," + res.img;
        this.loginForm.uuid = res.uuid;
      });
    },
    getCookie() {
      const username = Cookies.get("username");
      const password = Cookies.get("password");
      const rememberMe = Cookies.get("rememberMe");
      this.loginForm = {
        username: username === undefined ? this.loginForm.username : username,
        password:
          password === undefined ? this.loginForm.password : decrypt(password),
        rememberMe: rememberMe === undefined ? false : Boolean(rememberMe),
      };
    },
    handleLogin() {
      this.$refs.loginForm.validate((valid) => {
        if (valid) {
          this.loading = true;
          if (this.loginForm.rememberMe) {
            Cookies.set("username", this.loginForm.username, { expires: 30 });
            Cookies.set("password", encrypt(this.loginForm.password), {
              expires: 30,
            });
            Cookies.set("rememberMe", this.loginForm.rememberMe, {
              expires: 30,
            });
            Cookies.set("loginType", this.loginForm.loginType, { expires: 30 });
          } else {
            Cookies.remove("username");
            Cookies.remove("password");
            Cookies.remove("rememberMe");
            Cookies.remove("loginType");
          }

          this.$store
            .dispatch("Login", this.loginForm)
            .then((res) => {
              if (res.msg != "密码过期请重新设置密码") {
                // this.$router.push({ path: "/index" }).catch(() => {});
                const redirect = this.redirect;
                if (redirect == "/ykyx/"){ //测试环境跳转问题处理
                  this.$router.push({ path: "/" }).catch(()=>{});
                }else{
                  this.$router.push({ path: redirect}).catch(()=>{});
                }
                
              } else {
                this.$message.error("密码过期请重新设置密码");
                this.loading = false;
                this.open = true;
                if (this.loginForm.username != "") {
                  this.userName = this.loginForm.username;
                }
                this.oldPassword = this.loginForm.password;
                this.title = "重置密码";
                this.loginForm.username = "";
                this.loginForm.password = "";
                this.loginForm.code = "";
                return true;
              }
              // this.$router.push({ path: this.redirect || "/" }).catch(()=>{});
            })
            .catch(() => {
              this.loading = false;
              this.getCode();
            });
        }
      });
    },
    forgetPass() {
      this.open = true;
      this.title = "忘记密码";
      if (this.loginForm.username != "") {
        this.userName = this.loginForm.username;
      }
      this.oldPassword = this.loginForm.password;

    },
    passBlur() {
      let pwd = this.newPassword;
      let number = /\d/;
      let symbol = new RegExp(
        "[`~!@#$^&*()=|{}':;',\\[\\].<>《》/?~！@#￥……&*（）——|{}【】‘；：”“'。，、？ ]"
      );
      let letter = new RegExp(/[A-Za-z]+/);
      let letterCheck = letter.test(pwd);
      let numberCheck = number.test(pwd);
      let symbolCheck = symbol.test(pwd);
      if (pwd != "") {
        if (pwd.length < 6) {
          this.$message.error("密码长度不能小于6位数");
        } else if (!numberCheck) {
          this.$message.error("密码不包含数字，不符合规则");
        } else if (!letterCheck) {
          this.$message.error("密码不包含字母，不符合规则");
        } else if (!symbolCheck) {
          this.$message.error("密码不包含特殊符号，不符合规则");
        }
      } else {
        this.$message.error("密码不能为空");
      }
    },
    submitBtnClick() {
      let pwd = this.newPassword;
      let number = /\d/;
      let symbol = new RegExp(
        "[`~!@#$^&*()=|{}':;',\\[\\].<>《》/?~！@#￥……&*（）——|{}【】‘；：”“'。，、？ ]"
      );
      let letter = new RegExp(/[A-Za-z]+/);
      let letterCheck = letter.test(pwd);
      let numberCheck = number.test(pwd);
      let symbolCheck = symbol.test(pwd);
      if (this.userName == "") {
        this.$message.error("用户名不能为空");
      } else if (this.numCode == "") {
        this.$message.error("验证码不能为空");
      } else if (pwd == "") {
        this.$message.error("新密码不能为空");
      } else if (this.againPassword == "") {
        this.$message.error("确认新密码不能为空");
      } else if (this.newPassword != this.againPassword) {
        this.$message.error("确认密码与新密码输入不一致");
      } else {
        if (pwd.length < 6) {
          this.$message.error("密码长度不能小于6位数");
        } else if (!numberCheck) {
          this.$message.error("密码不包含数字，不符合规则");
        } else if (!letterCheck) {
          this.$message.error("密码不包含字母，不符合规则");
        } else if (!symbolCheck) {
          this.$message.error("密码不包含特殊符号，不符合规则");
        } else {
          appUpdatePassword({
            numCode: this.numCode,
            password: this.newPassword,
            phonenumber: this.userName,
          }).then((response) => {
            if (response.code == 200) {
              this.msgSuccess("修改成功");
              // this.$refs["loginForm"].resetFields();
              this.loginForm.password = this.newPassword;
              this.open = false;
              this.oldPassword = "";
              this.newPassword = "";
              this.againPassword = "";
              this.userName = "";
            }
          });
        }
      }
    },
  },
};
</script>
<style>
/* body{
  background: #e65582;
} */
</style>
<style rel="stylesheet/scss" lang="scss" scoped="scoped">
.login{
  width: 100%;
  min-width: 1200px; 
  margin: 0 auto;
  background: #fff;
  height: 100vh;
  .left{
    background: #f6cda7;
    min-width: 600px;
    height: 100vh;
  }
  .right{
    min-width: 600px;
  }
}
.leftCont{
  width: 750px;
  margin: 0 auto;
}
.logoName{
  margin: 86px 0 37px 34px;
  width: 184px;
  height: 45px;
  // width: 275px;
  // height: 67px;
  img{
    width: 100%;
  }
}
.yingwenIcon{
  margin-left: 34px;
  width: 260px;
  height: 20px;
  // width: 390px;
  // height: 30px;
  img{
    width: 100%;
  }
}
.leftImg{
  width: 750px;
  height: 625px;
  // width: 900px;
  // height: 750px;
  img{
    width: 100%;
  }
}
.forgetPassBox {
  div {
    label {
      display: block;
      margin: 20px 0 10px;
      font-size: 16px;
      color: #333;
      font-weight: 400;
    }
    em {
      margin-top: 4px;
      display: block;
      font-style: normal;
      font-size: 12px;
      color: #999;
      i {
        margin-right: 4px;
        color: red;
      }
    }
  }
}
.intMargin {
  margin-bottom: 6px !important;
}
.submitBtn {
  padding-bottom: 20px;
  margin-top: 50px;
  width: 100%;
}
.submitBtn .el-button--medium {
  width: 360px;
}
.checkPass {
  display: flex;
  justify-content: space-between;
  div {
    font-size: 14px;
    color: #fff;
    cursor: pointer;
  }
}
.pr {
  position: relative;
}
.englishSize{
  padding:0;
  margin:0;
  line-height: 40px;
  font-size: 20px;
  font-family: Microsoft YaHei;
  color: #FF8619;
}
.title {
  padding-bottom: 60px;
  text-align: left;
  color: #FF8619;
  font-size: 30px;
}

.login-form {
  background: #fff;
  padding-top: 100px;
  width: 400px;
  height: 640px;
  box-sizing: border-box;
  margin:0 auto;
  .el-input {
    height: 40px;
    input {
      height: 40px;
    }
  }
  .input-icon {
    height: 39px;
    width: 14px;
    margin-left: 2px;
  }
}
.login-tip {
  font-size: 13px;
  text-align: center;
  color: #bfbfbf;
}
.login-code {
  width: 33%;
  height: 38px;
  float: right;
  img {
    cursor: pointer;
    vertical-align: middle;
  }
}

.buttonLogo {
  height: 40px;
  box-sizing: border-box;
  background: #FF8315;
  border:1px solid #FF8315;
  border-radius: 25px;
  span {
    font-size: 18px;
  }
}
.login-code-img {
  height: 38px;
}
.el-input--medium {
  width: 100%;
}
 .box-input {
    position: relative;
    display: flex;
    justify-content: left;
  }

  .box-input:first-child {
    margin-top: 20px;
  }

  .box-input .el-form-item {
    width: 100%;
  }
  .e-code {
    display: inline-block;
    position: absolute;
    right: 20px;
    font-size: 12px;
    font-weight: 400;
    color: #FF7600;
    top: calc(50% - 5px);
    cursor: pointer
  }

  .gCode {
    color: #999;
  }
</style>
